package cn.yshujia.controller;

import cn.yshujia.domain.dto.PageDTO;
import cn.yshujia.domain.entity.TreeHole;
import cn.yshujia.domain.vo.ApiVO;
import cn.yshujia.domain.vo.PageVO;
import cn.yshujia.service.impl.TreeHoleServiceImpl;
import cn.yshujia.utils.RequestUtils;
import com.alibaba.fastjson2.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description 控制器
 */

@RestController
@Tag (name = "TreeHole", description = "树洞Api")
public class TreeHoleController {
	
	@Resource
	private TreeHoleServiceImpl service;
	
	@GetMapping ("/tree_hole/page")
	@Operation (summary = "获取树洞分页")
	public ApiVO<PageVO<TreeHole>> page(@RequestParam String dto) {
		PageDTO dtoPage = JSON.parseObject(dto, PageDTO.class);
		if (null == dtoPage) {
			return ApiVO.error();
		}
		return ApiVO.success(service.page(dtoPage));
	}
	
	@PostMapping ("/tree_hole/insert")
	@Operation (summary = "新增树洞")
	@PreAuthorize ("@sys.hasOnePermission('tree_hole:all', 'tree_hole:insert')")
	public ApiVO<Boolean> insert(@RequestBody TreeHole dto, HttpServletRequest req) {
		TreeHole treeHole = new TreeHole();
		treeHole.setContent(dto.getContent());
		treeHole.setIp(RequestUtils.getIp(req));
		Boolean result = service.insert(treeHole);
		if (result) {
			return ApiVO.success(true);
		}
		return ApiVO.error();
	}
	
	@GetMapping ("/admin/tree_hole/page")
	@Operation (summary = "admin 获取树洞分页")
	@PreAuthorize ("@sys.hasOnePermission('tree_hole:all')")
	public ApiVO<PageVO<TreeHole>> adminPage(@RequestParam String dto) {
		PageDTO dtoPage = JSON.parseObject(dto, PageDTO.class);
		if (null == dtoPage) {
			return ApiVO.error();
		}
		return ApiVO.success(service.adminPage(dtoPage));
	}
	
	@DeleteMapping ("/admin/tree_hole/delete")
	@Operation (summary = "admin 删除树洞")
	@PreAuthorize ("@sys.hasOnePermission('tree_hole:all')")
	public ApiVO<Boolean> delete(@RequestBody List<Long> ids) {
		Boolean result = service.remove(ids);
		if (result) {
			return ApiVO.success(true);
		}
		return ApiVO.error();
	}
}

